package com.tebiecloud.ali.server.controller.feign;

import com.alibaba.fastjson.JSONObject;
import com.tebiecloud.ali.client.constants.SmsTypeEnum;
import com.tebiecloud.ali.client.service.IAliSmsServiceClient;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.common.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 阿里云短信服务
 * @Author: tebie
 * @Date: 2019-09-24 10:11
 */
@RestController
@RequestMapping("/feign/sms")
public class AliSmsController implements IAliSmsServiceClient {

    /**
     * 发送验证码
     * @param phone
     * @param code
     * @param smsType 短信类型
     * @return
     */
    @Override
    @PostMapping("sendCode")
    public ResultBody<String> sendCode(@RequestParam("phone") String phone, @RequestParam("code") String code, @RequestParam("smsType") SmsTypeEnum smsType) {
        try {
            if(StringUtils.isEmpty(code)) {
                code = RandomValueUtils.randomNumeric(6);
            }

            JSONObject jsonParam = new JSONObject();
            jsonParam.put("code", code);
            Map<String, String> params = new HashMap<>();
            params.put("sms_type", smsType.getSmsType().toString());
            params.put("sub_type", smsType.getSubType().toString());
            params.put("param", jsonParam.toString());
            params.put("mobile", phone);

            String host = "http://112.74.179.177:47100/msg";
            String url = host + "/sms/send";

            String resp = NetworkUtils.doPostForm(url, params);
            JSONObject jsonResp = JsonUtils.str2Json(resp);
            if(jsonResp == null || !"100".equals(jsonResp.get("code"))) {
                return ResultBodyUtils.failed("发送失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBodyUtils.failed("发送异常");
        }

        return ResultBodyUtils.ok(code);
    }

}
